package cn.zbacm.api.img.controller;

import cn.zbacm.api.img.service.ImgService;
import cn.zbacm.api.security.CustomUser;
import cn.zbacm.api.user.entity.UserRole;
import cn.zbacm.api.user.repository.UserRoleRepository;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.List;

/**
 * @author 16639
 */
@RestController
public class ImgController {

  @Autowired
  private ImgService imgService;

  @Autowired
  private UserRoleRepository userRoleRepository;

  @PostMapping("/api/upload")
  @ApiOperation(value = "上传文件")
  public ResponseEntity<java.util.Map<String, Object>> uploadImage(MultipartFile file) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof AnonymousAuthenticationToken) {
      return new ResponseEntity(HttpStatus.UNAUTHORIZED);
    }
    CustomUser customUser = (CustomUser) authentication.getPrincipal();
    Integer userId = customUser.getUser().getId();
    List<UserRole> userRoles = userRoleRepository.findByUserId(userId);
    if (userRoles.isEmpty()) {
      return new ResponseEntity(HttpStatus.FORBIDDEN);
    }
    String backUrl = imgService.upload(file, "acmimg/");
    return new ResponseEntity<>(Collections.singletonMap("url", backUrl), HttpStatus.OK);
  }
}
